﻿using Newtonsoft.Json;
using System;
using System.Net;
using System.Text;

namespace PDFDesign.Common
{
    /// <summary>
    /// 操作类
    /// </summary>
    public class Utils
    {
        /// <summary>
        /// JSON格式化
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string JsonFormat(string json)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(json)) return json;
                dynamic parsedJson = JsonConvert.DeserializeObject(json);
                return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
            }
            catch
            {
                return json;
            }
        }

        /// <summary>
        /// HTTP POST
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postStr"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string HttpPost(string url, string postStr = "", Encoding encode = null)
        {
            var result = string.Empty;
            try
            {
                var webClient = new WebClient { Encoding = encode ?? Encoding.UTF8 };
                var sendData = Encoding.UTF8.GetBytes(postStr);
                webClient.Headers.Add("Content-Type", "application/json");
                webClient.Headers.Add("ContentLength", sendData.Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
                var readData = webClient.UploadData(url, "POST", sendData);
                result = Encoding.UTF8.GetString(readData);
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }
    }
}
